<?php

require "../../utility.php";
require "../../types.php";

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null) {
    // 检查权限
    $user_permission = getUserPermissionByUserId($conn, $user_id);
    if ($user_permission >= 1) {
        $order_query_str = "SELECT ID, orderTime, status, address FROM Orders ORDER BY orderTime DESC;";
        $order_query = $conn->query($order_query_str);

        $orders = [];
        while ($data = $order_query->fetch_row()) {
            $order = Order::fromArray($data);
            $book_query_str = "SELECT bookID, cnt FROM OrderBooks WHERE orderID = '$order->id'";
            $book_query = $conn->query($book_query_str);
            while ($book_data = $book_query->fetch_row()) {
                $book = OrderBook::fromArray($book_data);
                $order->addBook($book);
            }

            array_push($orders, $order);
        }

        http_response_code(200);

        echo json_encode($orders, JSON_UNESCAPED_UNICODE);
    }
}

?>